package com.clientservice;

import com.qqcommon.Message;
import com.qqcommon.MessageType;

import java.io.*;
import java.net.Socket;
import java.util.Date;

/**
 * @author wty
 * @date 2022/10/26 23:42
 * 该类用于传递文件
 */
public class FileClientService {

    /**
     *
     * @param sender 发送方
     * @param receiver 接收方
     * @param path 源路径
     * @param targetPath 接收方路径
     */
    // 发送文件
    @SuppressWarnings({"all"})
    public void sendFile(String sender,String receiver, String path,String targetPath) throws IOException {
        Message message = new Message();
        // 读取path文件路径的文件,放到message对象中
        BufferedInputStream bufferedInputStream = null;
        byte[] bytes = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(path));
            int fileSize = (int) (new File(path).length());
            bytes = new byte[fileSize];
            bufferedInputStream.read(bytes);
            message.setFileByte(bytes);
            message.setFileSize(fileSize);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (bufferedInputStream != null){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        message.setSendTime(new Date().toString());
        message.setSender(sender);
        message.setType(MessageType.MESSAGE_FILE);
        message.setPath(path);
        message.setTargetPath(targetPath);
        message.setReceiver(receiver);

        System.out.println(sender +"给" + receiver + " 发送文件:" +path + "到对方电脑路径:" + targetPath);

        // 发送
        Socket socket = ManageClientConnectServerThread.get(sender).getSocket();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectOutputStream.writeObject(message); // 注意这里发送的是message对象
        // outputStream.flush();

    }
}
